package com.guoxin.concurrentprogramming.chapter4.producerconsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者
 *
 * @author Administrator
 */
public class Producer implements Runnable {

    private volatile boolean isRunning = true;

    private BlockingQueue<PCData> queue;

    public Producer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    private static final AtomicInteger COUNT = new AtomicInteger();
    private static final int SLEEP_TIME = 1000;
    private static final Random RANDOM = new Random();

    public void run() {
        try {
            while (isRunning) {
                Thread.sleep(RANDOM.nextInt(SLEEP_TIME));
                PCData data = new PCData(COUNT.incrementAndGet());
                System.out.println(data + " is put into queue");
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
                    System.out.println("filed to put data: " + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void stop() {
        isRunning = false;
    }
}
